package utils

import (
	"regexp"
	"remote_cmd/models"
	"strings"
)

func IsValidIP(ip string) bool {
	reg := regexp.MustCompile("^((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))$")
	validIP := reg.FindAllString(ip, -1)
	return !(len(validIP) == 0)
}

func HandlerFilesName(fileInfos []string) map[string]interface{} {
	res := make(map[string]interface{})
	if len(fileInfos) == 0 {
		return res
	}
	var dirs []string
	var files []string
	for _, fileName := range fileInfos {
		if fileName[0] == 'd' {
			dirs = append(dirs, strings.Split(fileName, " ")[8])
		} else {
			files = append(files, strings.Split(fileName, " ")[8])
		}
	}
	res["dirs"] = dirs
	res["files"] = files
	return res
}

func DelSpace(strs []string) []string {
	var res []string
	for _, str := range strs {
		str = DelSpaceByString(str)
		res = append(res, str)
	}
	return res
}

func DelSpaceByString(str string) string {
	if !strings.Contains(str, "  ") {
		return str
	}
	str = strings.ReplaceAll(str, "  ", " ")
	return DelSpaceByString(str)
}

func IsValidFileOperationType(operationType string) bool {
	return operationType == models.ReadOnly || operationType == models.Edit
}
